#pragma once
#include <iostream>
#include <functional>
#include "Socket.hpp"
#include "InetAddr.hpp"
#include "Log.hpp"
#include "Protocol.hpp"
#include "Connection.hpp"
#include "NetCal.hpp"


using namespace log_ns;

class PackageParse
{
public:
    void Excute(Connection* conn)
    {
        while(true)
        {
            //我们能保证读到的是一个完整的报文吗？不能！
            //2.报文解析，提取报头和有效载荷
            std::string package = Decode(conn->Inbuffer());
            if(package.empty()) break;
            //我们能保证读到的是一个完整的报文吗？能！
            auto req = Factory::BuildRequestDafault();
            std::cout << "packgae: \n" << package << std::endl;
            //3.反序列化
            req->Deserialize(package);
            //4.业务处理
            //auto resp = _process(req); // 通过请求，得到应答
            auto resp = cal.Calculator(req);    
            //5.序列化应答
            std::string respjson;
            //resp->Serialize(&respjson);
            std::cout << "respjson: \n" << respjson << std::endl;
            //6.添加len长度报头
            respjson = Encode(respjson);
            std::cout << "respjson and header done: \n" << respjson << std::endl;
            //7.发回
            conn->AppendOutbuffer(respjson);
        }

        // 我们至少已经处理了一个请求，同时至少会有一个应答
        if(!conn->Outbuffer().empty()) conn->_handler_sender(conn); //方法1：直接发送数据
    }
private:
    NetCal cal;
};